<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\dao\crud;

use app\dao\BaseDao;
use app\model\crud\QuestionOptionModel;

/**
 * 题目选项数据访问层
 * Class QuestionOptionDao
 * @package app\dao\crud
 */
class QuestionOptionDao extends BaseDao
{
    /**
     * 设置模型
     * @return string
     */
    protected function setModel(): string
    {
        return QuestionOptionModel::class;
    }

    /**
     * 获取指定题目的选项列表
     * @param int $questionId
     * @param string $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOptionsByQuestionId(int $questionId, string $field = '*')
    {
        return $this->search(['question_id' => $questionId, 'is_del' => 0])
            ->field($field)
            ->order('sort asc, id asc')
            ->select()
            ->toArray();
    }

    /**
     * 批量保存选项
     * @param int $questionId
     * @param array $options
     * @return bool
     */
    public function batchSaveOptions(int $questionId, array $options): bool
    {
        // 先删除该题目的所有选项（软删除）
        $this->getModel()->where('question_id', $questionId)->update(['is_del' => 1]);

        // 批量插入新选项
        $insertData = [];
        foreach ($options as $index => $option) {
            $insertData[] = [
                'question_id' => $questionId,
                'option_key' => $option['option_key'] ?? chr(65 + $index), // 默认A、B、C、D...
                'option_content' => $option['option_content'] ?? '',
                'score' => $option['score'] ?? 0,
                'analysis' => $option['analysis'] ?? '',
                'icon' => $option['icon'] ?? '',
                'sort' => $option['sort'] ?? ($index + 1),
                'create_time' => time(),
                'update_time' => time(),
                'is_del' => 0,
            ];
        }

        if (empty($insertData)) {
            return false;
        }

        return $this->getModel()->insertAll($insertData) ? true : false;
    }

    /**
     * 根据选项ID获取选项详情
     * @param int $optionId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOptionDetail(int $optionId)
    {
        return $this->search(['id' => $optionId, 'is_del' => 0])
            ->with(['question'])
            ->find()
            ->toArray();
    }

    /**
     * 删除指定题目的所有选项
     * @param int $questionId
     * @return bool
     */
    public function deleteByQuestionId(int $questionId): bool
    {
        return $this->getModel()->where('question_id', $questionId)->update(['is_del' => 1]) ? true : false;
    }

    /**
     * 检查选项标识是否存在
     * @param int $questionId
     * @param string $optionKey
     * @param int $excludeId
     * @return bool
     */
    public function isOptionKeyExists(int $questionId, string $optionKey, int $excludeId = 0): bool
    {
        $query = $this->getModel()
            ->where('question_id', $questionId)
            ->where('option_key', $optionKey)
            ->where('is_del', 0);
        
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        
        return $query->count() > 0;
    }
}

